package contactbook.dao.impl;

import java.util.HashMap;

import contactbook.dao.AccountDAOInterface;
import contactbook.model.Account;

public class AccountDAO implements AccountDAOInterface {

	private static int cmpt = 0;
	
	private HashMap<Integer, Account> accounts;
	private HashMap<Integer, Integer> groupsOfAccounts;
	private HashMap<Integer, Integer> contactsOfAccounts;
	
	public AccountDAO() {
		accounts = new HashMap<Integer, Account>();
		groupsOfAccounts = new HashMap<Integer, Integer>();
		contactsOfAccounts = new HashMap<Integer, Integer>();
	}
	
	@Override
	public Account createAccount(Account account) {
		account.setId(getNextId());
		accounts.put(account.getId(), account);
		return account;
	}

	@Override
	public void deleteAccount(int accountId) {
		accounts.remove(accountId);
	}

	@Override
	public Account login(String login, String password) {
		Account log = null;
		for (Integer i : accounts.keySet()) {
			Account a = getAccountById(i.intValue());
			if (a.getLogin().equals(login) && a.getPassword().equals(password)) {
				a.setLogged(true);
				log = a;
			}
			else
				a.setLogged(false);
		}
		return log;
	}

	@Override
	public void logout() {
		for (Integer i : accounts.keySet()) {
			Account a = getAccountById(i.intValue());
			a.setLogged(false);
		}
	}

	@Override
	public Account getAccountById(int accountId) {
		return accounts.get(accountId);
	}

	@Override
	public void affectContact(int accountId, int contactId) {
		contactsOfAccounts.put(contactId, accountId);
	}

	@Override
	public void affectGroup(int accountId, int groupId) {
		groupsOfAccounts.put(groupId, accountId);
	}
	
	@Override
	public void deleteContact(int accoundId, int contactId) {
		contactsOfAccounts.remove(contactId);
	}

	@Override
	public void deleteGroup(int accountId, int groupId) {
		groupsOfAccounts.remove(groupId);
	}
	
	private static int getNextId() {
		return ++cmpt;
	}
}
